package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.HexUtil;
import com.ruoyi.system.domain.TBDevice;
import com.ruoyi.system.domain.TBOrder;
import com.ruoyi.system.netty.TCPServerHandler;
import com.ruoyi.system.service.ITBDeviceService;
import com.ruoyi.system.service.ITBOrderService;
import com.ruoyi.system.util.DevStatus;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.ReferenceCountUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TBOrderDevice;
import com.ruoyi.system.service.ITBOrderDeviceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单关联设备Controller
 * 
 * @author pspyy
 * @date 2022-03-09
 */
@RestController
@RequestMapping("/system/orderDevice")
@Api("订单关联设备")
public class TBOrderDeviceController extends BaseController
{
    @Autowired
    private ITBOrderDeviceService tBOrderDeviceService;
    @Autowired
    private ITBDeviceService deviceService;

    /**
     * 查询订单关联设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:list')")
    @GetMapping("/list")
    @ApiOperation("查询订单关联设备列表")
    public TableDataInfo list(TBOrderDevice tBOrderDevice)
    {
        startPage();
        List<TBOrderDevice> list = tBOrderDeviceService.selectTBOrderDeviceList(tBOrderDevice);
        return getDataTable(list);
    }

    /**
     * 导出订单关联设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:export')")
    @Log(title = "订单关联设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出订单关联设备列表")
    public void export(HttpServletResponse response, TBOrderDevice tBOrderDevice)
    {
        List<TBOrderDevice> list = tBOrderDeviceService.selectTBOrderDeviceList(tBOrderDevice);
        ExcelUtil<TBOrderDevice> util = new ExcelUtil<TBOrderDevice>(TBOrderDevice.class);
        util.exportExcel(response, list, "订单关联设备数据");
    }

    /**
     * 获取订单关联设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取订单关联设备详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tBOrderDeviceService.selectTBOrderDeviceById(id));
    }

    /**
     * 新增订单关联设备
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:add')")
    @Log(title = "订单关联设备", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增订单关联设备")
    public AjaxResult add(@RequestBody TBOrderDevice tBOrderDevice)
    {
        return toAjax(tBOrderDeviceService.insertTBOrderDevice(tBOrderDevice));
    }

    /**
     * 修改订单关联设备
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:edit')")
    @Log(title = "订单关联设备", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改订单关联设备")
    public AjaxResult edit(@RequestBody TBOrderDevice tBOrderDevice)
    {
        return toAjax(tBOrderDeviceService.updateTBOrderDevice(tBOrderDevice));
    }

    /**
     * 删除订单关联设备
     */
    @PreAuthorize("@ss.hasPermi('system:orderDevice:remove')")
    @Log(title = "订单关联设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation("删除订单关联设备")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tBOrderDeviceService.deleteTBOrderDeviceByIds(ids));
    }
    @GetMapping("/lockDevice/{ids}")
    @ApiOperation("锁车操作")
    public AjaxResult lockDevice(@PathVariable Long[] ids)
    {
        //批量锁定，状态处理，1：款项结清，锁车失败； 2：款项未结清，设备在线，下次上线再锁车；3:款项未结清，设备不在线，直接锁车
        List<Map<String,String>> resList = new ArrayList<>();
        for (Long id : ids) {
            TBOrderDevice orderDevice = tBOrderDeviceService.selectTBOrderDeviceById(id);
            boolean isPay = validateStatus(orderDevice.getOrderNum());
            String deviceStatue = orderDevice.getDeviceStatue();
            //Console.error(orderDevice.getDeviceName()+",当前状态："+deviceStatue);
            String msg = "款项结清，锁车失败";
            String code="100";
            TBDevice device = deviceService.selectTBDeviceById(orderDevice.getDeviceId());
            String deviceCode = device.getDeviceCode();

            boolean hasConnection = false;
            Map<String, String> devMap = TCPServerHandler.devMap;
            for (String value : devMap.values()) {
                if(value.toLowerCase().equals(deviceCode.toLowerCase())){
                    hasConnection=true;
                    break;
                }
            }
            if(isPay){
                if(hasConnection){
                    Map<String, Channel> connMap = TCPServerHandler.connMap;
                    String payRes="fe0202"+deviceCode+"fdfc";
                    ByteBuf bufff = Unpooled.buffer();
                    //返回锁定状态
                    bufff.writeBytes(HexUtil.decodeHex(payRes));
                    connMap.get(deviceCode).writeAndFlush(bufff);
                }
                msg="订单已完成付款，无法锁车";
            }else{
                //Console.error("判断状态："+deviceStatue);
                if(DevStatus.INTEND.equals(deviceStatue)||DevStatus.UNLINE.equals(deviceStatue)){
                    orderDevice.setDeviceStatue(DevStatus.LOCK);//锁车
                    tBOrderDeviceService.updateTBOrderDevice(orderDevice);
                    code="200";
                    msg="锁车成功";
                }else if(DevStatus.ONLINE.equals(deviceStatue)){
                    if(hasConnection){
                        //款项未结清，设备在线，下次上线再锁车
                        orderDevice.setDeviceStatue(DevStatus.WAIT_LOCK);//待锁车
                        tBOrderDeviceService.updateTBOrderDevice(orderDevice);
                        msg="设备正在运行，将在下次开机后自动锁定";
                    }else{
                        //未付清，且设备不在线
                        msg = "设备不在线，锁车失败";
                        code="100";
                    }
                }else if(DevStatus.LOCK.equals(deviceStatue)){
                    code="300";
                    msg="当前已处于锁车状态";
                }else{
                    code="300";
                    msg="当前已处于待锁车状态";
                }


            }
            Map<String,String> itemMap = new HashMap<>();
            itemMap.put("code",code);
            itemMap.put("msg",msg);
            itemMap.put("name",orderDevice.getDeviceName());
            resList.add(itemMap);
        }
        return AjaxResult.success(resList);
    }
    @GetMapping("/unLockDevice/{ids}")
    @ApiOperation("解锁操作")
    public AjaxResult unLockDevice(@PathVariable Long[] ids)
    {
        List<Map<String,String>> resList = new ArrayList<>();
        for (Long id : ids) {
            String code="200";
            String msg="";
            TBOrderDevice orderDevice = tBOrderDeviceService.selectTBOrderDeviceById(id);
            String deviceStatue = orderDevice.getDeviceStatue();
            String deviceStr="";
            switch (deviceStatue){
                case  "0":
                    deviceStr="就绪";
                        break;
                case  "1":
                    deviceStr="在线";
                    break;
                case  "2":
                    deviceStr="离线";
                    break;
            }
            if(DevStatus.LOCK.equals(deviceStatue)||DevStatus.WAIT_LOCK.equals(deviceStatue)){
                orderDevice.setDeviceStatue(DevStatus.INTEND);//解锁为就绪状态
                tBOrderDeviceService.updateTBOrderDevice(orderDevice);
                msg="解锁成功";
            }else{
                code="300";
                msg="设备状态为"+deviceStr+"，无需解锁";
            }
            Map<String,String> itemMap = new HashMap<>();
            itemMap.put("code",code);
            itemMap.put("msg",msg);
            itemMap.put("name",orderDevice.getDeviceName());
            resList.add(itemMap);
        }
        return AjaxResult.success(resList);
    }

    private boolean validateStatus(String orderNum){
        boolean isPay = false;
        List<String> valList =  tBOrderDeviceService.validateStatus(orderNum);
        System.out.println(valList);
        for (String valStr : valList) {
            String[] valArr = valStr.split(",");
            if(valArr!=null&&valArr.length>0){
                String firstStr = valArr[0];
                String secondStr = valArr[1];
                if(firstStr.equals("0")){
                    isPay=true;
                    break;
                }else if("1".equals(secondStr)){
                    isPay=false;
                    break;
                }else{
                    isPay=true;
                }

            }
        }
        return isPay;
    }

}
